package com.express.controller;

import com.express.bean.MapArea;
import com.express.bean.Message;
import com.express.mvc.ResponseBody;
import com.express.service.AdminService;
import com.express.service.ExpressService;
import com.express.util.JSONUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: laixiangdong
 * @Date 2020/12/05
 */
public class AdminController {
    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        Boolean login = AdminService.login(userName, password);
        Message message = null;
        if (login) {
            message = new Message(0, "登录成功");
            Date date = new Date();
            String ip = req.getRemoteAddr();
            AdminService.updateLoginTimeAndIP(userName, date, ip);
            req.getSession().setAttribute("userName", userName);
        } else {
            message = new Message(-1, "登录失败");
        }
        String json = JSONUtil.toJSON(message);
        return json;
    }
    @ResponseBody("/admin/admin.do")
    public String admin(HttpServletRequest req, HttpServletResponse resp){
        Message message = null;
        String userName = (String) req.getSession().getAttribute("userName");
        if (userName != null) {
            message = new Message(0, "查询成功", userName);
        }else {
            message = new Message(-1, "查询失败", null);
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/admin/logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        session.invalidate();
        Cookie[] cookies = req.getCookies();
        for (Cookie c:cookies) {
            c.setMaxAge(0);
            resp.addCookie(c);
        }

        try {
            resp.sendRedirect("/admin/login.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Message message = new Message(0,"退出成功",null);
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/admin/map.do")
    public String map(HttpServletRequest req, HttpServletResponse resp){
        Message message = null;
        List<MapArea> data = AdminService.map();
        if (data != null) {
            message = new Message(0, "查询成功", data);
        }else {
            message = new Message(-1, "查询失败", null);
        }
        return JSONUtil.toJSON(message);
    }

}
